<template>
  <div class="warehousing-create">
    <el-page-header content="入库管理" @back="router.back" style="margin-bottom: 16px" />
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span style="font-size: 35px;">基础信息</span>
         </div>
      </template>
      <el-form ref="ruleFormRef" style="max-width: 1000px" :model="ruleForm" label-width="auto">
    <el-container>
      <el-aside width="500px">
        <el-form-item label="入库单号">
              <el-input v-model="ruleForm.warehousingCode" placeholder="自动获取系统编号" class="readonly-input" readonly>
                <template #append>
                  <el-button @click="generateWarehousingCode" :loading="generatingWarehousingCode">
                    自动生成
                  </el-button>
                </template>
              </el-input>
    </el-form-item>
            <el-form-item label="仓库名称">
      <el-select v-model="ruleForm.warehouseId" @change="loadStorageLocations" placeholder="请选择">
                <el-input v-model="warehousingname" class="option-input" placeholder="请输入" />
        <el-option v-for="item in warehouseOptions" :label="item.warehouseName" :value="item.warehouseId" />
      </el-select>
    </el-form-item>
    <el-form-item label="关联单号">
              <el-input v-model="selectedStockinGoodsNo" placeholder="请选择关联进货订单" readonly style="cursor: pointer;"
                @click="openStockinGoodsDialog" :disabled="!linkStockinGoods">
        <template #append>
          <el-button @click="openStockinGoodsDialog" icon="Search" :disabled="!linkStockinGoods">选择</el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="联系人">
      <el-input v-model="ruleForm.contact" :disabled="linkStockinGoods" />
    </el-form-item>
            <el-form-item label="经办人">
              <el-input v-model="selectedUserName" placeholder="请选择经办人" readonly style="cursor: pointer;"
                @click="openUserDialog">
        <template #append>
          <el-button @click="openUserDialog" icon="Search">选择</el-button>
        </template>
      </el-input>
    </el-form-item>
      </el-aside>

          <el-aside width="500px">
            <el-form-item label="入库类型" style="margin-left: 28px;">
      <el-select v-model="ruleForm.warehousingTypeId" placeholder="请选择">
                <el-option v-for="item in handlerOptions" :label="item.warehousingName"
                  :value="item.warehousingTypeId" />
      </el-select>
    </el-form-item>
            <el-form-item label="入库日期" style="margin-left: 28px;">
              <el-date-picker v-model="ruleForm.storageDate" type="date" aria-label="Pick a date" placeholder="请选择"
                style="width: 100%" />
    </el-form-item>
            <el-form-item style="margin-left: 28px;">
      <el-checkbox v-model="linkStockinGoods" @change="handleLinkStockinGoodsChange">关联进货单号</el-checkbox>
    </el-form-item>
            <el-form-item label="供应商" style="margin-left: 28px;" > 
      <el-select v-model="ruleForm.supplierId" placeholder="请选择" :disabled="linkStockinGoods">
                <el-input v-model="suppliermodel.suppliercode" class="option-input" placeholder="请输入"
                  :disabled="linkStockinGoods" />
        <el-option v-for="item in supplierOptions" :label="item.supplierName" :value="item.supplierId" />
        
      </el-select>
    </el-form-item>
            <el-form-item label="联系方式" style="margin-left: 28px;">
      <el-input v-model="ruleForm.contactInformation" :disabled="linkStockinGoods" />
    </el-form-item>
          </el-aside>
    </el-container>
    <el-form-item label="备注">
      <el-input v-model="ruleForm.warehousingDescription" type="textarea" />
    </el-form-item>
    </el-form>
    </el-card>

    <!-- 入库明细 -->
    <el-card shadow="never" style="margin-top: 16px;">
      <template #header>
        <div class="card-header">
          <span style="font-size: 35px;">入库明细</span>
          <el-button type="primary" @click="openProductDialog" >新增</el-button>
        </div>
      </template>
      
      <!-- 入库明细表格 -->
      <el-table :data="warehousingDetails" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" width="120" />
        <el-table-column prop="productCode" label="货品编号" width="120" />
        <el-table-column prop="productTypeName" label="货品类型" width="100" />
        <el-table-column prop="productUnit" label="规格型号" width="100" />
        <el-table-column prop="productSpecification" label="单位" width="80" />
        <el-table-column prop="currentStock" label="当前库存" width="100" />
        <el-table-column prop="totalQuantity" label="进货数量" width="100" />
        <el-table-column prop="storedQuantity" label="已入库数量" width="100" />
        <el-table-column prop="currentQuantity" label="本次入库数量" width="120">
          <template #default="scope">
            <el-input-number v-model="scope.row.currentQuantity" :min="0"
              :max="Math.max(0, scope.row.totalQuantity - scope.row.storedQuantity)" size="small" :controls="false"
              @change="calculateRowAmount(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="storageLocation" label="入库库区" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.storagelocationId" placeholder="请选择" size="small" style="width: 100%"
              @focus="loadStorageLocations" @change="handleDetailStorageLocationChange(scope.row)">
              <el-option v-for="location in storageLocationOptions" :label="location.storagelocationName"
                :value="location.storagelocationId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="仓位" width="220">
          <template #default="scope">
            <el-select
              v-model="scope.row.positionId"
              placeholder="请选择仓位"
              size="small"
              style="width: 100%"
              filterable
              clearable
              :loading="scope.row.positionLoading"
              @focus="ensurePositionOptionsForRow(scope.row)"
              @change="handleDetailPositionChange(scope.row)"
            >
              <el-option
                v-for="option in scope.row.positionOptions || []"
                :key="option.value"
                :label="option.label"
                :value="option.value"
                :disabled="option.isFull"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="进货单价" width="100">
          <template #default="scope">
            <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2" size="small" :controls="false"
              @change="calculateRowAmount(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="currentAmount" label="进货金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.currentAmount?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="batchNumber" label="批次号" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.batchNumber" size="small" placeholder="请输入批次号" />
          </template>
        </el-table-column>
        <el-table-column prop="productionDate" label="生产日期" width="120">
          <template #default="scope">
            <el-date-picker v-model="scope.row.productionDate" type="date" placeholder="选择日期" size="small"
              style="width: 100%" />
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.remarks" size="small" placeholder="请输入备注" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">
              移除
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <el-icon size="48" color="#c0c4cc">
              <Box />
            </el-icon>
            <p>暂无入库明细</p>
            <p>点击上方"新增"按钮添加产品</p>
          </div>
        </template>
      </el-table>

      <!-- 统计信息 -->
      <div class="summary-info">
        <span>合计：</span>
        <span style="margin-left: 20px;">本次数量：{{ totalCurrentQuantity }}</span>
        <span style="margin-left: 20px;">已入库数量：{{ totalStoredQuantity }}</span>
        <span style="margin-left: 20px;">入库数量：{{ totalWarehousingQuantity }}</span>
        <span style="margin-left: 20px;">入库金额：¥{{ totalWarehousingAmount.toFixed(2) }}</span>
      </div>
    </el-card>

 <el-card>
  <el-button type="success" style="float: right; margin-bottom: 15px;" @click="snve">保存</el-button>
 </el-card>
    <!-- 关联进货订单选择对话框 -->
    <el-dialog v-model="stockinGoodsDialogVisible" title="选择进货单" width="80%" :close-on-click-modal="false">
      <!-- 搜索条件 -->
      <el-form :model="stockinGoodsSearchForm" :inline="true" class="search-form">
        <el-form-item label="进货单号">
          <el-input v-model="stockinGoodsSearchForm.stockinGoodsNo" placeholder="请输入进货单号" clearable />
        </el-form-item>
        <el-form-item label="进货人">
          <el-input v-model="stockinGoodsSearchForm.userName" placeholder="请输入进货人" clearable />
        </el-form-item>
        <el-form-item label="进货部门">
          <el-input v-model="stockinGoodsSearchForm.organizationName" placeholder="请输入进货部门" clearable />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select v-model="stockinGoodsSearchForm.stockinGoodsStatus" placeholder="请选择单据状态" clearable>
            <el-option label="草稿" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="部分入库" :value="2" />
            <el-option label="已入库" :value="3" />
            <el-option label="已关闭" :value="4" />
            <el-option label="已作废" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="stockinGoodsSearchForm.supplierId" placeholder="请选择供应商" clearable>
            <el-option v-for="item in supplierOptions" :key="item.supplierId" :label="item.supplierName"
              :value="item.supplierId" />
          </el-select>
        </el-form-item>
        <el-form-item label="进货日期">
          <el-date-picker v-model="stockinGoodsSearchForm.dateRange" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchStockinGoods" icon="Search">查询</el-button>
          <el-button @click="resetStockinGoodsSearch" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 进货订单表格 -->
      <el-table :data="stockinGoodsList" style="width: 100%" @row-click="selectStockinGoods" highlight-current-row
        v-loading="stockinGoodsTableLoading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="选择" width="55">
          <template #default="scope">
            <el-radio :label="scope.row.stockinGoodsId" v-model="selectedStockinGoodsId"
              @change="selectStockinGoods(scope.row)">
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="stockinGoodsNo" label="进货单号" width="190" />
        <el-table-column prop="stockinGoodsStatusText" label="单据状态" width="100" />
        <el-table-column prop="stockinGoodsDate" label="进货日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.stockinGoodsDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="150" />
        <el-table-column prop="organizationName" label="进货部门" width="140" />
        <el-table-column prop="stockinUser" label="进货人" width="100" />
        <el-table-column prop="stockinGoodsCount" label="货品数量" width="100" />
        <el-table-column prop="stockinGoodsAmount" label="进货金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.stockinGoodsAmount?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <div class="pagination-info">总{{ stockinGoodsPagination.total }}条</div>
        <el-pagination v-model:current-page="stockinGoodsPagination.pageindex"
          v-model:page-size="stockinGoodsPagination.pagesize" :page-sizes="[10, 20, 50, 100]"
          :total="stockinGoodsPagination.total" layout="prev, pager, next" @size-change="handleStockinGoodsSizeChange"
          @current-change="handleStockinGoodsCurrentChange" />
        <el-select v-model="stockinGoodsPagination.pagesize" style="width: 100px; margin-left: 10px"
          @change="handleStockinGoodsSizeChange">
          <el-option label="10条/页" :value="10" />
          <el-option label="20条/页" :value="20" />
          <el-option label="50条/页" :value="50" />
          <el-option label="100条/页" :value="100" />
        </el-select>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockinGoodsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStockinGoodsSelection"
            :disabled="!selectedStockinGoods">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 经办人选择对话框 -->
    <el-dialog v-model="userDialogVisible" title="选择人员" width="70%" :close-on-click-modal="false">
      <div class="user-selection-container">
        <!-- 搜索条件 -->
        <div class="search-section">
          <el-input v-model="userSearchKeyword" placeholder="请输入姓名或编号" clearable
            style="width: 300px; margin-right: 10px;" />
          <el-button type="primary" @click="searchUsers" icon="Search">查询</el-button>
        </div>

        <!-- 主体内容 -->
        <div class="content-section">
          <!-- 左侧组织架构树 -->
          <div class="organization-tree">
            <div class="tree-header">组织架构</div>
            <el-tree :data="organizationTree" :props="treeProps" node-key="organizationId"
              @node-click="handleOrganizationClick" :expand-on-click-node="false" :highlight-current="true"
              v-loading="treeLoading">
              <template #default="{ node, data }">
                <span class="tree-node">
                  <span>{{ data.organizationName || data.label }}</span>
                </span>
              </template>
            </el-tree>
          </div>

          <!-- 右侧用户列表 -->
          <div class="user-list">
            <div class="list-header">
              已选择 {{ selectedUser ? 1 : 0 }} 人
              <el-tag v-if="selectedUser" closable @close="clearSelectedUser" class="selected-user-tag">
                {{ selectedUser.userName }}
              </el-tag>
            </div>
            <div class="user-grid" v-loading="userLoading">
              <div v-for="user in filteredUsers" :key="user.userId"
                :class="['user-item', { 'selected': selectedUser && selectedUser.userId === user.userId }]"
                @click="selectUser(user)">
                <div class="user-avatar">{{ user.userName.charAt(0) }}</div>
                <div class="user-info">
                  <div class="user-name">{{ user.userName }}</div>
                  <div class="user-account">{{ user.userAccount }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUserSelection" :disabled="!selectedUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 产品选择对话框 -->
    <el-dialog v-model="productDialogVisible" title="选择产品" width="80%" :close-on-click-modal="false">
      <!-- 搜索条件 -->
      <el-form :model="productSearchForm" :inline="true" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="productSearchForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchProducts" icon="Search">查询</el-button>
          <el-button @click="resetProductSearch" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 产品表格 -->
      <el-table :data="productList" style="width: 100%" @selection-change="handleProductSelection"
        v-loading="productTableLoading">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="产品名称" width="120" />
        <el-table-column prop="productCode" label="产品编号" width="120" />
        <el-table-column prop="producttypeName" label="产品类型" width="100" />
        <el-table-column prop="productUnit" label="规格" width="80" />
        <el-table-column prop="productspecification" label="单位" width="80" />
        <el-table-column prop="productInmoney" label="入库参考价" width="120">
          <template #default="scope">
            ¥{{ scope.row.productInmoney?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="inventoryCurrtnumber" label="当前库存" width="100" />
        <el-table-column prop="supplierName" label="供应商" width="120" />
        <el-table-column prop="warehouseName" label="仓库" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="!showAllProducts">
        <el-pagination v-model:current-page="productPagination.pageindex" v-model:page-size="productPagination.pagesize"
          :page-sizes="[10, 20, 50, 100]" :total="productPagination.total" layout="sizes, prev, pager, next, jumper"
          @size-change="handleProductSizeChange" @current-change="handleProductCurrentChange" />
      </div>
      <div class="pagination-container" v-else>
        <div class="pagination-info">已加载全部货品，共 {{ productPagination.total }} 条</div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProductSelection"
            :disabled="selectedProducts.length === 0">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
 
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch, toRaw } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type TableInstance,
} from 'element-plus'
import { Search, Refresh, Box } from '@element-plus/icons-vue'
import axios from 'axios'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'
const router = useRouter()
const route = useRoute()

const editingWarehousingId = ref<number | null>(
  route.query.warehousingId ? Number(route.query.warehousingId) : null,
)

const isEdit = computed(() => Boolean(editingWarehousingId.value))

onMounted(async () => {
  getwarehousingtype()
  show()
  getsupplier()
  loadUnitOptions()
  if (isEdit.value && editingWarehousingId.value) {
    await loadWarehousingDetailForEdit(editingWarehousingId.value)
  } else {
    await newgetwarehousing()
  }
})
const ruleForm = reactive({
  "warehousingCode": "",
  "warehousingTypeId": '',
  "warehousingCodeState": 1,
  "storageDate": null as Date | string | null,
  "warehouseId": '',
  "stockinGoodsId": '',
  "productid": '',
   "userId": '',
  "contact": "",
  "contactInformation": "",
  "warehousingNum": "",
  "warehousingMoney": '',
  "organizationId": '',
  "warehousingDescription": "",
  "supplierId": '',
  "documentCreator": "李四",
  "reviewerPeople": "王五"
})
const warehousingMeta = reactive({
  userName: '',
  productName: '',
  organizationName: '',
  stockinGoodsNo: '',
  supplierName: '',
  warehouseName: '',
  warehousingCodeStateName: '',
  warehousingName: ''
})
//显示入库类型
const handlerOptions = ref([{
  "warehousingTypeId": '',
  "warehousingName": ""
}]);
const getwarehousingtype = () => {
  myaxios.get('/api/Warehousing/GetWarehousingType')
    .then(res => {
      handlerOptions.value = res.data.data;
    }
  )
}
//显示仓库
const warehouseOptions = ref([{
  "warehouseId": '',
  "warehouseName": "",
}]);
const warehousingname = ref("");
watch(warehousingname, () => {
  show();
})
const show = () => {
  myaxios.get("/api/Warehousing/GetWarehouse", { params: { name: warehousingname.value } })
    .then(res => {
      warehouseOptions.value = res.data.data;
      updateWarehouseMeta()
  }
  )
}
const supplierOptions = ref([{
  "supplierId": "",
    "supplierName": "",
}]);
const suppliermodel = reactive({
  suppliercode: '',
    supplierStatus: '',
    industryId: '',
    userid: '',
})
watch(suppliermodel, () => {
  getsupplier();
})
const getsupplier = () => {
  myaxios.get("/api/Warehousing/GetSupplierForExport", {
        params: {
            suppliercode: suppliermodel.suppliercode, //供应商名称/编号
            supplierStatus: suppliermodel.supplierStatus, //状态
            industryId: suppliermodel.industryId, //行业
            userId: suppliermodel.userid, //进货负责人
        }
    })
    .then(res => {
      supplierOptions.value = res.data.data;
      updateSupplierMeta()
  }
  )
}

// 编号生成相关
const generatingWarehousingCode = ref(false)
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const idxA = TIME_SEGMENT_ORDER.indexOf(a)
      const idxB = TIME_SEGMENT_ORDER.indexOf(b)
      if (idxA === -1 && idxB === -1) return 0
      if (idxA === -1) return 1
      if (idxB === -1) return -1
      return idxA - idxB
    })
  const timePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const serialLength = Number(rule?.serialLength ?? 3)
  const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
  return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode, targetName }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode, targetName }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateWarehousingCode = async () => {
  if (generatingWarehousingCode.value) return
  generatingWarehousingCode.value = true
  try {
    ruleForm.warehousingCode = await requestNumber('Warehousing', '入库单')
    ElMessage.success('编号生成成功')
  } catch (error: any) {
    ElMessage.error(error?.message || '生成编号失败')
  } finally {
    generatingWarehousingCode.value = false
  }
}

// 关联进货单号复选框
const linkStockinGoods = ref(false)
const selectedStockinGoodsNo = ref('')

// 关联进货订单选择对话框相关
const stockinGoodsDialogVisible = ref(false)
const selectedStockinGoods = ref<any>(null)
const selectedStockinGoodsId = ref<number | null>(null)
const stockinGoodsTableLoading = ref(false)
const stockinGoodsList = ref<any[]>([])

// 进货订单搜索表单
const stockinGoodsSearchForm = reactive({
  stockinGoodsNo: '',
  userName: '',
  organizationName: '',
  stockinGoodsStatus: null as number | null,
  supplierId: null as number | null,
  dateRange: null as [string, string] | null
})

// 进货订单分页信息
const stockinGoodsPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  total: 0
})

// 经办人选择对话框相关
const userDialogVisible = ref(false)
const selectedUser = ref<any>(null)
const selectedUserName = ref('')
const userSearchKeyword = ref('')
const userLoading = ref(false)
const treeLoading = ref(false)
const allUsers = ref<any[]>([])
const filteredUsers = ref<any[]>([])
const organizationTree = ref<any[]>([])
const currentOrganizationId = ref<number | null>(null)

// 关联进货单号复选框变化处理
const handleLinkStockinGoodsChange = (checked: boolean) => {
  if (!checked) {
    // 取消关联时，清空相关数据
    selectedStockinGoods.value = null
    selectedStockinGoodsNo.value = ''
    warehousingMeta.stockinGoodsNo = ''
    selectedStockinGoodsId.value = null
    ruleForm.stockinGoodsId = ''
    // 清空从进货订单获取的数据
    ruleForm.contact = ''
    ruleForm.supplierId = ''
    ruleForm.contactInformation = ''
    ruleForm.productid = ''
    ruleForm.warehousingMoney = ''
    ruleForm.warehousingNum = ''
  }
}

// 打开关联进货订单选择对话框
const openStockinGoodsDialog = () => {
  if (!linkStockinGoods.value) {
    ElMessage.warning('请先勾选"关联进货单号"')
    return
  }
  stockinGoodsDialogVisible.value = true
  searchStockinGoods()
}

// 搜索进货订单
const searchStockinGoods = async () => {
  stockinGoodsTableLoading.value = true
  try {
    const params: any = {
      stockinGoodsNo: stockinGoodsSearchForm.stockinGoodsNo || undefined,
      stockinGoodsStatus: stockinGoodsSearchForm.stockinGoodsStatus !== null ? stockinGoodsSearchForm.stockinGoodsStatus : undefined,
      supplierId: stockinGoodsSearchForm.supplierId || undefined,
      pageindex: stockinGoodsPagination.pageindex,
      pagesize: stockinGoodsPagination.pagesize
    }
    
    // 处理日期范围
    if (stockinGoodsSearchForm.dateRange && stockinGoodsSearchForm.dateRange.length === 2) {
      params.beginDate = stockinGoodsSearchForm.dateRange[0]
      params.endDate = stockinGoodsSearchForm.dateRange[1]
    }
    
    // 处理进货人和进货部门的查询（需要在后端支持，这里先不传）
    
    const response = await myaxios.get('/api/StockinGoods/GetStockingoods', { params })
    
    if (response.data && (response.data.success || response.data.code === 200)) {
      stockinGoodsList.value = response.data.data?.data || []
      stockinGoodsPagination.total = response.data.data?.listCount || 0
      
      // 添加状态文本
      stockinGoodsList.value.forEach((item: any) => {
        switch (item.stockinGoodsStatus) {
          case 0:
            item.stockinGoodsStatusText = '草稿'
            break
          case 1:
            item.stockinGoodsStatusText = '待审核'
            break
          case 2:
            item.stockinGoodsStatusText = '部分入库'
            break
          case 3:
            item.stockinGoodsStatusText = '已入库'
            break
          case 4:
            item.stockinGoodsStatusText = '已关闭'
            break
          case 5:
            item.stockinGoodsStatusText = '已作废'
            break
          default:
            item.stockinGoodsStatusText = '未知'
        }
      })
    } else {
      ElMessage.error('获取进货订单列表失败')
    }
  } catch (error) {
    console.error('搜索进货订单失败:', error)
    ElMessage.error('搜索进货订单失败')
  } finally {
    stockinGoodsTableLoading.value = false
  }
}

// 重置进货订单搜索条件
const resetStockinGoodsSearch = () => {
  stockinGoodsSearchForm.stockinGoodsNo = ''
  stockinGoodsSearchForm.userName = ''
  stockinGoodsSearchForm.organizationName = ''
  stockinGoodsSearchForm.stockinGoodsStatus = null
  stockinGoodsSearchForm.supplierId = null
  stockinGoodsSearchForm.dateRange = null
  stockinGoodsPagination.pageindex = 1
  searchStockinGoods()
}

// 选择进货订单
const selectStockinGoods = (row: any) => {
  selectedStockinGoods.value = row
  selectedStockinGoodsId.value = row.stockinGoodsId
}

// 确认选择进货订单
const confirmStockinGoodsSelection = async () => {
  if (selectedStockinGoods.value) {
    const stockinGoods = selectedStockinGoods.value
    // 设置关联的进货订单ID
    ruleForm.stockinGoodsId = stockinGoods.stockinGoodsId
    selectedStockinGoodsNo.value = stockinGoods.stockinGoodsNo
    warehousingMeta.stockinGoodsNo = stockinGoods.stockinGoodsNo || ''
    
    // 从进货订单中获取联系人、供应商、联系方式
    ruleForm.contact = stockinGoods.stockinContact || ''
    ruleForm.supplierId = stockinGoods.supplierId || ''
    ruleForm.contactInformation = stockinGoods.stockinContactPhone || ''
    
    // 从进货订单中获取货品ID、入库金额、入库数量
    ruleForm.productid = stockinGoods.productid || ''
    ruleForm.warehousingMoney = stockinGoods.stockinGoodsAmount || 0
    ruleForm.warehousingNum = stockinGoods.stockinGoodsCount || 0
    warehousingMeta.supplierName = stockinGoods.supplierName || warehousingMeta.supplierName
    warehousingMeta.productName = stockinGoods.productName || warehousingMeta.productName
    
    // 获取进货订单明细并填充到入库明细
    await loadStockinGoodsDetails(stockinGoods.stockinGoodsId)
    
    stockinGoodsDialogVisible.value = false
    ElMessage.success('关联进货订单成功，已自动加载货品明细')
  } else {
    ElMessage.warning('请选择一个进货订单')
  }
}

// 提取明细列表的辅助函数
const extractDetailList = (data: any): any[] => {
  const candidates = [
    data?.goodsDetails,
    data?.GoodsDetails,
    data?.stockinGoodsDetails,
    data?.StockinGoodsDetails,
    data?.stockinGoodsDetail,
    data?.StockinGoodsDetail,
    data?.details,
    data?.detail,
    data?.detailList,
    data?.DetailList,
    data?.items,
    data?.Items,
    data?.records,
    data?.Records,
    data?.data,
    data?.Data,
    data?.list,
    data?.List,
    data?.result,
    data?.Result,
    data?.stockinGoods?.goodsDetails,
    data?.stockinGoods?.stockinGoodsDetails,
    data?.stockinGoods?.detailList,
    data?.stockinGoods?.details,
    data?.baseInfo?.goodsDetails,
    data?.baseInfo?.stockinGoodsDetails,
    data?.baseInfo?.detailList,
    data?.baseInfo?.details,
  ]

  for (const candidate of candidates) {
    if (Array.isArray(candidate) && candidate.length > 0) {
      return candidate
    }
  }
  return []
}

// 转换进货订单明细项为入库明细格式
const transformStockinDetailToWarehousing = async (detailItem: any) => {
  const productId = detailItem.productId || detailItem.productID || detailItem.id || 0
  if (!productId) {
    console.warn('明细项缺少货品ID，跳过:', detailItem)
    return null
  }

  try {
    // 获取货品详细信息
    const productResponse = await myaxios.get('/api/Product/GetProductById', {
      params: { productId }
    })

    let productInfo: any = {}
    if (productResponse && productResponse.data && (productResponse.data.success || productResponse.data.code === 200)) {
      productInfo = productResponse.data.data || {}
    }

    // 获取数量、单价、金额等信息
    const quantity = Number(detailItem.quantity || detailItem.stockinGoodsCount || detailItem.purchaseCount || 0)
    const unitPrice = Number(detailItem.purchasePrice || detailItem.unitPrice || detailItem.stockinPrice || 0)
    const amount = Number(detailItem.amount || detailItem.totalAmount || detailItem.totalPrice || detailItem.purchaseAmount || (quantity * unitPrice))
    const storedQuantity = Number(detailItem.inputNum || detailItem.storedQuantity || 0) // 已入库数量
    const currentQuantity = Math.max(0, quantity - storedQuantity) // 本次可入库数量 = 进货数量 - 已入库数量

    // 转换为入库明细格式
    return {
      productId: productId,
      productName: productInfo.productName || detailItem.productName || '',
      productCode: productInfo.productCode || detailItem.productCode || '',
      productTypeName: productInfo.producttypeName || detailItem.producttypeName || detailItem.categoryName || '',
      productSpecification: productInfo.productspecification || detailItem.productSpecification || detailItem.specification || '',
      productUnit: productInfo.productUnit || detailItem.productUnit || detailItem.unit || '',
      currentStock: productInfo.inventoryCurrtnumber || detailItem.currentStock || 0,
      totalQuantity: quantity, // 进货数量
      storedQuantity: storedQuantity, // 已入库数量
      currentQuantity: currentQuantity, // 本次入库数量（默认等于可入库数量）
      storagelocationId: null,
      unitPrice: unitPrice, // 进货单价
      currentAmount: currentQuantity * unitPrice, // 本次入库金额
      batchNumber: detailItem.batchNumber || detailItem.batchNo || '',
      productionDate: detailItem.productionDate ? new Date(detailItem.productionDate) : null,
        remarks: detailItem.remarks || detailItem.remark || '',
        positionOptions: [],
        positionLoading: false,
        positionId: detailItem.positionId || detailItem.PositionId || null
    }
  } catch (error: any) {
    console.error(`获取货品 ${productId} 信息失败:`, error)
    // 即使获取货品信息失败，也使用明细项中的基本信息
    const quantity = Number(detailItem.quantity || detailItem.stockinGoodsCount || 0)
    const unitPrice = Number(detailItem.purchasePrice || detailItem.unitPrice || 0)
    const storedQuantity = Number(detailItem.inputNum || detailItem.storedQuantity || 0)
    const currentQuantity = Math.max(0, quantity - storedQuantity)

    return {
      productId: productId,
      productName: detailItem.productName || '',
      productCode: detailItem.productCode || '',
      productTypeName: detailItem.producttypeName || detailItem.categoryName || '',
      productSpecification: detailItem.productSpecification || detailItem.specification || '',
      productUnit: detailItem.productUnit || detailItem.unit || '',
      currentStock: detailItem.currentStock || 0,
      totalQuantity: quantity,
      storedQuantity: storedQuantity,
      currentQuantity: currentQuantity,
      storagelocationId: null,
      unitPrice: unitPrice,
      currentAmount: currentQuantity * unitPrice,
      batchNumber: detailItem.batchNumber || detailItem.batchNo || '',
      productionDate: detailItem.productionDate ? new Date(detailItem.productionDate) : null,
      remarks: detailItem.remarks || detailItem.remark || '',
      positionOptions: [],
      positionLoading: false,
      positionId: detailItem.positionId || detailItem.PositionId || null
    }
  }
}

// 加载进货订单明细
const loadStockinGoodsDetails = async (stockinGoodsId: number) => {
  if (!selectedStockinGoods.value) {
    return
  }
  
  try {
    // 调用进货订单详情接口，获取所有明细项
    let res = await myaxios.get('/api/StockinGoods/GetStockingoodsDetail', {
      params: { stockinGoodsId }
    }).catch(() => null)

    // 如果新接口失败，尝试旧接口
    if (!res || res.data?.code !== 200) {
      res = await myaxios.get('/api/StockinGoods/GetStockinGoodsDetail', {
        params: { stockinGoodsId }
      })
    }

    const result = res?.data || {}
    if (result.code === 200) {
      const data = result.data || {}

      // 提取明细列表
      const detailList = extractDetailList(data)

      if (detailList.length === 0) {
        ElMessage.warning('该进货订单没有货品明细数据')
        return
      }

      // 清空现有明细
      warehousingDetails.value = []
      
      // 遍历明细列表，转换为入库明细格式并添加
      const promises = detailList.map((item: any) => transformStockinDetailToWarehousing(item))
      const transformedDetails = await Promise.all(promises)

      // 过滤掉转换失败的项目
      const validDetails = transformedDetails.filter((detail: any) => detail !== null)

      if (validDetails.length === 0) {
        ElMessage.warning('未能加载任何货品明细')
        return
      }

      // 添加到入库明细
      warehousingDetails.value.push(...validDetails)
      validDetails.forEach((detail:any) => {
        ensureDetailPositionMeta(detail)
        if (detail.storagelocationId) {
          void loadPositionOptionsForRow(detail)
        }
      })
      
      ElMessage.success(`已加载 ${validDetails.length} 条货品明细`)
    } else {
      ElMessage.error(result.message || '获取进货订单明细失败')
    }
  } catch (error: any) {
    console.error('加载进货订单明细失败:', error)
    ElMessage.error('加载货品明细失败，请手动添加货品')
  }
}

// 添加货品到入库明细的辅助函数
const addProductToDetails = async (productId: number, quantity: number, amount: number, remark: string) => {
  try {
    // 获取货品详细信息
    const productResponse = await myaxios.get('/api/Product/GetProductById', {
      params: { productId }
    })
    
    let productInfo: any = {}
    if (productResponse && productResponse.data && (productResponse.data.success || productResponse.data.code === 200)) {
      productInfo = productResponse.data.data || {}
    }
    
    // 计算单价
    const unitPrice = quantity > 0 ? amount / quantity : 0
    
    // 添加到入库明细
    warehousingDetails.value.push({
      productId: productId,
      productName: productInfo.productName || '',
      productCode: productInfo.productCode || '',
      productTypeName: productInfo.producttypeName || '',
      productSpecification: productInfo.productspecification || '',
      productUnit: productInfo.productUnit || '',
      currentStock: productInfo.inventoryCurrtnumber || 0,
      totalQuantity: quantity, // 进货数量
      storedQuantity: 0, // 已入库数量，初始为0
      currentQuantity: quantity, // 本次入库数量，默认等于进货数量
      storagelocationId: null,
      unitPrice: unitPrice, // 进货单价
      currentAmount: amount, // 进货金额
      batchNumber: '',
      productionDate: null,
      remarks: remark,
      positionOptions: [],
      positionLoading: false,
      positionId: null
    })
  } catch (error: any) {
    console.error(`获取货品 ${productId} 信息失败:`, error)
    // 即使获取货品信息失败，也添加基本信息
    const unitPrice = quantity > 0 ? amount / quantity : 0
    warehousingDetails.value.push({
      productId: productId,
      productName: '',
      productCode: '',
      productTypeName: '',
      productSpecification: '',
      productUnit: '',
      currentStock: 0,
      totalQuantity: quantity,
      storedQuantity: 0,
      currentQuantity: quantity,
      storagelocationId: null,
      unitPrice: unitPrice,
      currentAmount: amount,
      batchNumber: '',
      productionDate: null,
      remarks: remark,
      positionOptions: [],
      positionLoading: false,
      positionId: null
    })
  }
  updateProductNameMeta()
}

// 进货订单分页处理
const handleStockinGoodsSizeChange = () => {
  stockinGoodsPagination.pageindex = 1
  searchStockinGoods()
}

const handleStockinGoodsCurrentChange = () => {
  searchStockinGoods()
}

// 格式化日期
const formatDate = (date: any) => {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD')
}

// 经办人选择相关功能

// 树形组件属性
const treeProps = {
  children: 'children',
  label: 'label'
}

// 打开经办人选择对话框
const openUserDialog = () => {
  userDialogVisible.value = true
  loadOrganizations()
  loadAllUsers()
}

// 加载组织架构
const loadOrganizations = async () => {
  treeLoading.value = true
  try {
    const response = await myaxios.get('/api/Organization/GetOrganizationTree', {
      params: { parentid: 0 }
    })
    
    if (response.data && Array.isArray(response.data)) {
      // 后台返回的已经是树形结构，但需要转换字段名以适配前端
      organizationTree.value = transformOrganizationTree(response.data)
    } else {
      ElMessage.error('获取组织架构失败')
    }
  } catch (error) {
    console.error('加载组织架构失败:', error)
    ElMessage.error('加载组织架构失败')
  } finally {
    treeLoading.value = false
  }
}

// 转换组织架构树形数据，将后台返回的字段映射为前端需要的字段
const transformOrganizationTree = (treeData: any[]): any[] => {
  return treeData.map(node => {
    const transformedNode: any = {
      organizationId: node.id,
      organizationName: node.label,
      organizationCode: node.code,
      parentId: node.parentId,
      children: node.children ? transformOrganizationTree(node.children) : []
    }
    return transformedNode
  })
}

// 加载所有用户
const loadAllUsers = async () => {
  userLoading.value = true
  try {
    const response = await myaxios.get('/api/Supplier/GetUser')
    if (response.data.success || response.data.code === 200) {
      allUsers.value = response.data.data || []
      filteredUsers.value = allUsers.value
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    userLoading.value = false
  }
}

// 处理组织节点点击
const handleOrganizationClick = (data: any) => {
  // 兼容两种数据结构：后台返回的id和转换后的organizationId
  const orgId = data.organizationId || data.id
  currentOrganizationId.value = orgId
  filterUsersByOrganization(orgId)
}

// 按组织筛选用户
const filterUsersByOrganization = (organizationId: number) => {
  if (organizationId) {
    filteredUsers.value = allUsers.value.filter(user => user.organizationId === organizationId)
  } else {
    filteredUsers.value = allUsers.value
  }
  // 如果有搜索关键词，同时应用搜索筛选
  if (userSearchKeyword.value) {
    applySearchFilter()
  }
}

// 搜索用户
const searchUsers = () => {
  applySearchFilter()
}

// 应用搜索筛选
const applySearchFilter = () => {
  let users = currentOrganizationId.value 
    ? allUsers.value.filter(user => user.organizationId === currentOrganizationId.value)
    : allUsers.value
    
  if (userSearchKeyword.value) {
    const keyword = userSearchKeyword.value.toLowerCase()
    users = users.filter(user => 
      user.userName.toLowerCase().includes(keyword) || 
      user.userAccount.toLowerCase().includes(keyword)
    )
  }
  
  filteredUsers.value = users
}

// 选择用户
const selectUser = (user: any) => {
  selectedUser.value = user
}

// 清除已选择的用户
const clearSelectedUser = () => {
  selectedUser.value = null
}

// 确认用户选择
const confirmUserSelection = () => {
  if (selectedUser.value) {
    ruleForm.userId = selectedUser.value.userId
    ruleForm.organizationId = selectedUser.value.organizationId
    selectedUserName.value = selectedUser.value.userName
    warehousingMeta.userName = selectedUser.value.userName || ''
    warehousingMeta.organizationName = selectedUser.value.organizationName || ''
    userDialogVisible.value = false
    selectedUser.value = null
    userSearchKeyword.value = ''
    currentOrganizationId.value = null
    ElMessage.success('经办人选择成功')
  } else {
    ElMessage.warning('请选择一个经办人')
  }
}
// 入库明细相关变量
const warehousingDetails = ref<any[]>([])
type ShelfInfo = {
  shelfId: number
  shelfCode: string
  shelfName: string
  storagelocationId: number
}
type PositionOption = {
  value: number
  label: string
  shelfId: number
  shelfCode: string
  shelfName: string
  positionCode?: string
  positionRow?: number
  positionColumn?: number
  positionLayer?: number
  positionDepth?: number
  isFull?: boolean
}
const SHELF_PAGE_SIZE = 9999
const POSITION_PAGE_SIZE = 999
const shelfCacheByWarehouse = reactive<Record<number, ShelfInfo[]>>({})
const positionCacheByShelf = reactive<Record<number, PositionOption[]>>({})
const ensureDetailPositionMeta = (detail: any) => {
  if (!detail) return
  if (detail.positionOptions === undefined) detail.positionOptions = []
  if (detail.positionLoading === undefined) detail.positionLoading = false
  if (detail.positionId === undefined) detail.positionId = null
}

// 库位选择相关
const storageLocationOptions = ref([{
   "storagelocationId": "",
        "storagelocationName": "",
}])

// 产品选择对话框相关变量
const productDialogVisible = ref(false)
const productTableLoading = ref(false)
const productList = ref<any[]>([])
const selectedProducts = ref<any[]>([])
const unitOptions = ref<any[]>([])
const showAllProducts = ref(true)
const ALL_PRODUCTS_PAGE_SIZE = 9999

// 产品搜索表单
const productSearchForm = reactive({
  productName: '',
  unitId: null as number | null,
})

// 产品分页信息
const productPagination = reactive({
  pageindex: 1,
  pagesize: ALL_PRODUCTS_PAGE_SIZE,
  total: 0
})

// 统计计算属性
const totalCurrentQuantity = computed(() => {
  return warehousingDetails.value.reduce((sum, item) => sum + (item.currentQuantity || 0), 0)
})

const totalStoredQuantity = computed(() => {
  return warehousingDetails.value.reduce((sum, item) => sum + (item.storedQuantity || 0), 0)
})

const totalWarehousingQuantity = computed(() => {
  return warehousingDetails.value.reduce((sum, item) => sum + (item.currentQuantity || 0), 0)
})

const totalWarehousingAmount = computed(() => {
  return warehousingDetails.value.reduce((sum, item) => sum + (item.currentAmount || 0), 0)
})

// 打开产品选择对话框
const openProductDialog = () => {
  productDialogVisible.value = true
  showAllProducts.value = true
  productPagination.pagesize = ALL_PRODUCTS_PAGE_SIZE
  productPagination.pageindex = 1
  searchProducts()
}

const loadUnitOptions = async () => {
  try {
    const res = await myaxios.get('/api/Unit/GetUnitList')
    if (res.data && (res.data.success || res.data.code === 200)) {
      unitOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('加载单位列表失败:', error)
  }
}

// 搜索产品
const searchProducts = async () => {
  productTableLoading.value = true
  try {
    const isShowAll = showAllProducts.value
    const response = await myaxios.get('/api/Product/GetProduct', {
      params: {
        Pageindex: isShowAll ? 1 : productPagination.pageindex,
        PageSize: isShowAll ? ALL_PRODUCTS_PAGE_SIZE : productPagination.pagesize,
        ProductName: productSearchForm.productName,
        UnitId: productSearchForm.unitId || undefined,
        number: 1
      }
    })
    
    if (response.data.success || response.data.code === 200) {
      const payload = response.data.data || {}
      productList.value = payload.data || payload.items || []
      productPagination.total = payload.listCount || productList.value.length || 0
    } else {
      ElMessage.error('获取产品列表失败')
    }
  } catch (error) {
    console.error('搜索产品失败:', error)
    ElMessage.error('搜索产品失败')
  } finally {
    productTableLoading.value = false
  }
}

// 重置产品搜索
const resetProductSearch = () => {
  productSearchForm.productName = ''
  productSearchForm.unitId = null
  productPagination.pageindex = 1
  showAllProducts.value = true
  productPagination.pagesize = ALL_PRODUCTS_PAGE_SIZE
  searchProducts()
}

// 处理产品选择
const handleProductSelection = (selection: any[]) => {
  selectedProducts.value = selection
}

// 产品分页处理
const handleProductSizeChange = (val: number) => {
  showAllProducts.value = false
  productPagination.pagesize = val
  productPagination.pageindex = 1
  searchProducts()
}

const handleProductCurrentChange = (val: number) => {
  showAllProducts.value = false
  productPagination.pageindex = val
  searchProducts()
}

// 确认产品选择
const confirmProductSelection = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择至少一个产品')
    return
  }

  let addedCount = 0
  let skippedCount = 0
  
  selectedProducts.value.forEach(product => {
    // 检查是否已存在
    const exists = warehousingDetails.value.find(item => item.productId === product.productId)
    if (!exists) {
      warehousingDetails.value.push({
        productId: product.productId,
        //inventoryId: product.inventoryId || 0, // 库存ID
        productName: product.productName,
        productCode: product.productCode,
        productTypeName: product.producttypeName,
        productSpecification: product.productspecification || '',
        productUnit: product.productUnit,
        currentStock: product.inventoryCurrtnumber || 0, // 当前库存
        totalQuantity: 500, // 默认进货数量
        storedQuantity: 50, // 默认已入库数量
        currentQuantity: 0, // 本次入库数量
        storagelocationId: null, // 入库库位ID
        unitPrice: product.productInmoney || 0, // 进货单价
        currentAmount: 0, // 进货金额
        batchNumber: '', // 批次号
        productionDate: null, // 生产日期
        remarks: '', // 备注
        positionOptions: [],
        positionLoading: false,
        positionId: null,
      })
      addedCount++
    } else {
      skippedCount++
    }
  })

  productDialogVisible.value = false
  selectedProducts.value = []
  
  if (addedCount > 0) {
    let message = `成功添加 ${addedCount} 个产品到入库明细`
    if (skippedCount > 0) {
      message += `，跳过 ${skippedCount} 个已存在的产品`
    }
    ElMessage.success(message)
  } else {
    ElMessage.warning('所选产品已存在于入库明细中')
  }
}

// 计算行金额
const calculateRowAmount = (row: any) => {
  row.currentAmount = (row.currentQuantity || 0) * (row.unitPrice || 0)
}

// 移除明细
const removeDetail = (index: number) => {
  warehousingDetails.value.splice(index, 1)
  ElMessage.success('移除成功')
  updateProductNameMeta()
}

// 加载库位列表
const loadStorageLocations = async () => {
  if (!ruleForm.warehouseId) {
    ElMessage.warning('请先选择仓库')
    return
  }
  
  try {
    const response = await myaxios.get('/api/Warehouse/GetStoragelocation', {
      params: {
        warehouseId: ruleForm.warehouseId,
        name: '',
        userid: '',
        storagelocationstate: 1, // 只获取启用状态的库位
        pageindex: 1,
        pagesize: 1000 // 获取所有库位
      }
    })
    
    if (response.data.success || response.data.code === 200) {
      storageLocationOptions.value = response.data.data.data 
    } else {
      ElMessage.error('获取库区列表失败')
    }
  } catch (error) {
    console.error('加载库区列表失败:', error)
    ElMessage.error('加载库区列表失败')
  }
}

const formatPositionParts = (position: any) => {
  const parts: string[] = []
  const row = Number(position.positionRow)
  if (Number.isFinite(row) && row > 0) parts.push(`${row}排`)
  const column = Number(position.positionColumn)
  if (Number.isFinite(column) && column > 0) parts.push(`${column}列`)
  const layer = Number(position.positionLayer)
  if (Number.isFinite(layer) && layer > 0) parts.push(`${layer}层`)
  const depth = Number(position.positionDepth)
  if (Number.isFinite(depth) && depth > 0) parts.push(`${depth}深`)
  return parts.length ? parts.join('') : `仓位${position.positionId || ''}`
}

const buildPositionOptionLabel = (shelf: ShelfInfo | null, position: any) => {
  const descriptor = formatPositionParts(position) || position.positionCode
  if (descriptor) {
    return descriptor
  }
  return shelf?.shelfCode || shelf?.shelfName || `仓位${position.positionId || ''}`
}

const fetchShelvesForWarehouse = async (warehouseId: number) => {
  if (!warehouseId) return []
  if (shelfCacheByWarehouse[warehouseId]) {
    return shelfCacheByWarehouse[warehouseId]
  }
  try {
    const response = await myaxios.get('/api/Shelf/GetShelfPage', {
      params: {
        Pageindex: 1,
        PageSize: SHELF_PAGE_SIZE,
        warehouseId,
      },
    })
    const list = (response.data?.data?.data || []) as ShelfInfo[]
    shelfCacheByWarehouse[warehouseId] = list
    return list
  } catch (error) {
    console.error('加载货架列表失败:', error)
    return []
  }
}

const getShelvesForLocation = async (warehouseId: number, storagelocationId: number) => {
  if (!warehouseId || !storagelocationId) return []
  const shelves = await fetchShelvesForWarehouse(warehouseId)
  return shelves.filter(shelf => Number(shelf.storagelocationId) === storagelocationId)
}

const fetchPositionOptionsForShelf = async (shelf: ShelfInfo) => {
  if (!shelf?.shelfId) return []
  const shelfId = Number(shelf.shelfId) || 0
  if (!shelfId) return []
  if (positionCacheByShelf[shelfId]) {
    return positionCacheByShelf[shelfId]
  }
  try {
    const response = await myaxios.get('/api/WarePosition/GetWarePositionPage', {
      params: {
        Pageindex: 1,
        PageSize: POSITION_PAGE_SIZE,
        shelfId,
      },
    })
    const list = response.data?.data?.data || []
    const options = list
      .map((position: any) => {
        const value = Number(position.positionId) || 0
        if (!value) return null
        return {
          value,
          label: buildPositionOptionLabel(shelf, position),
          shelfId,
          shelfCode: shelf.shelfCode || '',
          shelfName: shelf.shelfName || '',
          positionCode: position.positionCode,
          positionRow: position.positionRow,
          positionColumn: position.positionColumn,
          positionLayer: position.positionLayer,
          positionDepth: position.positionDepth,
          isFull: Number(position.isWarehouseFull ?? position.IsWarehouseFull ?? 0) === 1,
        }
      })
      .filter((option: PositionOption | null): option is PositionOption => Boolean(option))
    positionCacheByShelf[shelfId] = options
    return options
  } catch (error) {
    console.error(`加载货架 ${shelfId} 的仓位失败:`, error)
    return []
  }
}

const loadPositionOptionsForRow = async (detail: any) => {
  if (!detail) return
  ensureDetailPositionMeta(detail)
  const warehouseId = Number(ruleForm.warehouseId) || 0
  const locationId = Number(detail.storagelocationId) || 0
  detail.positionLoading = true
  if (!warehouseId || !locationId) {
    detail.positionOptions = []
    detail.positionLoading = false
    return
  }
  try {
    const shelves = await getShelvesForLocation(warehouseId, locationId)
    if (!shelves.length) {
      detail.positionOptions = []
      return
    }
    const positionLists = await Promise.all(shelves.map(shelf => fetchPositionOptionsForShelf(shelf)))
    detail.positionOptions = positionLists.flat()
  } catch (error) {
    console.error('加载仓位选项失败:', error)
    detail.positionOptions = []
  } finally {
    detail.positionLoading = false
  }
}

const ensurePositionOptionsForRow = (detail: any) => {
  if (!detail) return
  ensureDetailPositionMeta(detail)
  if (!detail.positionOptions?.length && detail.storagelocationId) {
    void loadPositionOptionsForRow(detail)
  }
}

const handleDetailStorageLocationChange = (detail: any) => {
  if (!detail) return
  ensureDetailPositionMeta(detail)
  detail.positionId = null
  detail.positionOptions = []
  if (!detail.storagelocationId) return
  void loadPositionOptionsForRow(detail)
}

const handleDetailPositionChange = (detail: any) => {
  if (!detail || !detail.positionId) {
    return
  }
  ensureDetailPositionMeta(detail)
  const option = detail.positionOptions?.find((item: PositionOption) => item.value === detail.positionId)
  if (option?.isFull) {
    detail.positionId = null
    ElMessage.warning('该仓位已满，无法入库')
  }
}

// 将前端入库明细数据转换为后端API格式
const convertDetailsToApiFormat = (details: any[], warehousingId: number) => {
  // 使用 toRaw 去除响应式，然后手动创建纯对象
  return details.map(detail => {
    // 将响应式对象转换为普通对象
    const rawDetail = toRaw(detail)
    
    // 处理日期：如果是 Date 对象，转换为 ISO 字符串；如果是字符串，直接使用；否则使用当前时间
    let inputTime: string | Date = new Date()
    if (rawDetail.productionDate) {
      if (rawDetail.productionDate instanceof Date) {
        inputTime = rawDetail.productionDate
      } else if (typeof rawDetail.productionDate === 'string') {
        inputTime = rawDetail.productionDate
      } else {
        inputTime = new Date(rawDetail.productionDate)
      }
    }
    
    // 创建纯对象，确保所有值都是普通值
    // 注意：warehousingId 不需要在每个 detail 中，它已经在 BatchCreateInboundDetailDTO 的顶层
    return {
      productId: Number(rawDetail.productId) || 0,
      quantityPurchased: Number(rawDetail.totalQuantity) || 0,
      inputNum: Number(rawDetail.storedQuantity) || 0,
      unreceivedNum: Math.max(0, (Number(rawDetail.totalQuantity) || 0) - (Number(rawDetail.storedQuantity) || 0)),
      storagelocationId: Number(rawDetail.storagelocationId) || 0,
      newInputNum: Number(rawDetail.currentQuantity) || 0,
      costPrice: Number(rawDetail.unitPrice) || 0,
      totalCostPrice: Number(rawDetail.currentAmount) || 0,
      inputBatch: String(rawDetail.batchNumber || ''),
      inputTime: inputTime,
      inputNote: String(rawDetail.remarks || ''),
      positionId: Number(rawDetail.positionId) || 0
    }
  })
}
const saving = ref(false)

const snve = async () => {
  if (saving.value) return
  saving.value = true
  try {
    // 如果是新增且编号为空，自动生成编号
    if (!isEdit.value && !ruleForm.warehousingCode) {
      await generateWarehousingCode()
      if (!ruleForm.warehousingCode) {
        ElMessage.warning('请先生成入库单号')
        saving.value = false
        return
      }
    }
    let warehousingId: number | null = isEdit.value ? editingWarehousingId.value || null : null
    const savedHeaderId = await saveWarehousingHeader(warehousingId)
    if (!savedHeaderId) return
    warehousingId = savedHeaderId
    const detailResult = await saveWarehousingDetails(warehousingId)
    if (detailResult) {
      ElMessage.success('入库单保存成功')
          router.push('/GetWarehousing')
    }
  } finally {
    saving.value = false
  }
}

const saveWarehousingDetails = async (warehousingId: number | null) => {
  if (!warehousingId) {
    ElMessage.error('缺少入库单ID，无法保存明细')
    return false
  }
  if (!warehousingDetails.value.length) {
    return true
  }

  const detailsData = {
    warehousingId,
    details: convertDetailsToApiFormat(warehousingDetails.value, warehousingId),
  }
  try {
    const res = await myaxios.post('/api/Warehousing/BatchCreateInboundDetail', detailsData)
    if (res.data.code === 200 || res.data.success) {
      return true
    }
    ElMessage.error(res.data.message || '入库明细保存失败')
    return false
  } catch (error) {
          console.error('保存入库明细失败:', error)
          ElMessage.error('保存入库明细失败，请重试')
    return false
      }
}

const buildWarehousingPayload = () => {
  // 处理入库日期
  let storageDate: Date
  if (ruleForm.storageDate) {
    const dateObj = ruleForm.storageDate as any
    storageDate = dateObj instanceof Date ? dateObj : new Date(dateObj)
  } else {
    storageDate = new Date()
  }

  // 只发送后端 CreateWarehousingDTO 需要的字段
  return {
      warehousingCode: String(ruleForm.warehousingCode || ''),
      warehousingTypeId: Number(ruleForm.warehousingTypeId) || 0,
      warehousingCodeState: Number(ruleForm.warehousingCodeState) || 1,
    storageDate: storageDate,
      warehouseId: Number(ruleForm.warehouseId) || 0,
    stockinGoodsId: ruleForm.stockinGoodsId ? Number(ruleForm.stockinGoodsId) : 0,
    productid: ruleForm.productid ? Number(ruleForm.productid) : 0,
    userId: ruleForm.userId ? Number(ruleForm.userId) : 0,
      contact: String(ruleForm.contact || ''),
      contactInformation: String(ruleForm.contactInformation || ''),
    warehousingNum: Number(ruleForm.warehousingNum) || 0,
    warehousingMoney: Number(ruleForm.warehousingMoney) || 0,
    organizationId: ruleForm.organizationId ? Number(ruleForm.organizationId) : 0,
      warehousingDescription: String(ruleForm.warehousingDescription || ''),
    supplierId: ruleForm.supplierId ? Number(ruleForm.supplierId) : 0,
      documentCreator: String(ruleForm.documentCreator || ''),
    reviewerPeople: String(ruleForm.reviewerPeople || '')
  }
}

const saveWarehousingHeader = async (currentId: number | null) => {
  try {
    if (isEdit.value && currentId) {
      // 编辑时使用 WarehousingDTO，包含更多字段
      const updatePayload = {
        ...buildWarehousingPayload(),
        warehousingId: currentId,
    userName: warehousingMeta.userName || '',
    productName: warehousingMeta.productName || '',
    organizationName: warehousingMeta.organizationName || '',
    stockinGoodsNo: warehousingMeta.stockinGoodsNo || '',
    supplierName: warehousingMeta.supplierName || '',
    warehouseName: warehousingMeta.warehouseName || '',
    warehousingCodeStateName: warehousingMeta.warehousingCodeStateName || '',
    warehousingName: warehousingMeta.warehousingName || ''
  }
      const res = await myaxios.put('/api/Warehousing/UpdateWarehousing', updatePayload)
      if (res.data.code === 200 || res.data.success) {
        newgetwarehousingId.value = currentId
        return currentId
      }
      ElMessage.error(res.data.message || '更新入库单失败')
      return null
    } else {
      // 新增时只使用 CreateWarehousingDTO 需要的字段
      const payload = buildWarehousingPayload()
      const res = await myaxios.post('/api/Warehousing/CreateWarehousing', payload)
      if (res.data.code === 200 || res.data.success) {
        await newgetwarehousing()
        if (!newgetwarehousingId.value) {
          ElMessage.error('未能获取新入库单号，请刷新后重试')
          return null
        }
        return Number(newgetwarehousingId.value)
      }
      ElMessage.error(res.data.message || '创建入库单失败')
      return null
      }
  } catch (error: any) {
      console.error('保存入库单失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '保存入库单失败，请重试'
    ElMessage.error(errorMessage)
    return null
  }
}

//显示最新库位
const newgetwarehousingId = ref<number | null>(null)
const newgetwarehousing = async () => {
  try {
    const res = await myaxios.get("/api/Warehousing/NewGetWarehousing", {
      params: {
        warehouseId: ruleForm.warehouseId || undefined
      }
    })
    if (res.data && res.data.data) {
      newgetwarehousingId.value = res.data.data.warehousingId
      return newgetwarehousingId.value
    }
  } catch (error) {
    console.error('获取最新入库单失败:', error)
  }
  return null
}

const updateSupplierMeta = () => {
  const supplier = supplierOptions.value.find(item => item.supplierId === ruleForm.supplierId)
  warehousingMeta.supplierName = supplier?.supplierName || ''
}

const updateWarehouseMeta = () => {
  const warehouse = warehouseOptions.value.find(item => item.warehouseId === ruleForm.warehouseId)
  warehousingMeta.warehouseName = warehouse?.warehouseName || ''
}

const updateWarehousingTypeMeta = () => {
  const type = handlerOptions.value.find(item => item.warehousingTypeId === ruleForm.warehousingTypeId)
  warehousingMeta.warehousingName = type?.warehousingName || ''
}

const updateCodeStateMeta = () => {
  const map: Record<number, string> = {
    0: '草稿',
    1: '待审核',
    2: '已完成',
    3: '驳回',
  }
  warehousingMeta.warehousingCodeStateName = map[Number(ruleForm.warehousingCodeState)] || ''
}

const updateProductNameMeta = () => {
  warehousingMeta.productName = warehousingDetails.value
    .map(item => item.productName)
    .filter(Boolean)
    .join(',')
}

watch(warehousingDetails, () => {
  updateProductNameMeta()
}, { deep: true })
watch(() => ruleForm.supplierId, () => updateSupplierMeta())
watch(() => ruleForm.warehouseId, () => updateWarehouseMeta())
watch(() => ruleForm.warehousingTypeId, () => updateWarehousingTypeMeta())
watch(() => ruleForm.warehousingCodeState, () => updateCodeStateMeta())

const loadWarehousingDetailForEdit = async (warehousingId: number) => {
  try {
    const res = await myaxios.get('/api/Warehousing/GetWarehousingDetail', {
      params: { warehousingId },
    })
    if (!(res.data.success || res.data.code === 200)) {
      ElMessage.error(res.data.message || '获取入库详情失败')
      return
    }
    const data = res.data.data || {}
    ruleForm.warehousingCode = data.warehousingCode || ''
    ruleForm.warehousingTypeId = data.warehousingTypeId || ''
    ruleForm.warehousingCodeState = data.warehousingCodeState ?? 1
    ruleForm.storageDate = data.storageDate ? new Date(data.storageDate) : ''
    ruleForm.warehouseId = data.warehouseId || ''
    ruleForm.stockinGoodsId = data.stockinGoodsId || ''
    ruleForm.productid = data.productid || ''
    ruleForm.userId = data.userId || ''
    ruleForm.contact = data.contact || ''
    ruleForm.contactInformation = data.contactInformation || ''
    ruleForm.warehousingNum = data.warehousingNum || ''
    ruleForm.warehousingMoney = data.warehousingMoney || ''
    ruleForm.organizationId = data.organizationId || ''
    ruleForm.warehousingDescription = data.warehousingDescription || ''
    ruleForm.supplierId = data.supplierId || ''
    ruleForm.documentCreator = data.documentCreator || ''
    ruleForm.reviewerPeople = data.reviewerPeople || ''
    selectedUserName.value = data.userName || ''
    selectedStockinGoodsNo.value = data.stockinGoodsNo || ''
    selectedStockinGoodsId.value = data.stockinGoodsId || null
    linkStockinGoods.value = Boolean(data.stockinGoodsId)
    warehousingDetails.value = (data.detailList || []).map(mapApiDetailToForm)
    warehousingDetails.value.forEach(detail => {
      ensureDetailPositionMeta(detail)
      if (detail.storagelocationId) {
        void loadPositionOptionsForRow(detail)
      }
    })
    editingWarehousingId.value = data.warehousingId
    newgetwarehousingId.value = data.warehousingId
    warehousingMeta.userName = data.userName || ''
    warehousingMeta.organizationName = data.organizationName || ''
    warehousingMeta.stockinGoodsNo = data.stockinGoodsNo || ''
    warehousingMeta.supplierName = data.supplierName || ''
    warehousingMeta.warehouseName = data.warehouseName || ''
    warehousingMeta.warehousingCodeStateName = data.warehousingCodeStateName || ''
    warehousingMeta.warehousingName = data.warehousingName || ''
    warehousingMeta.productName = data.productName || ''
    updateProductNameMeta()
  } catch (error) {
    console.error('获取入库详情失败:', error)
    ElMessage.error('获取入库详情失败')
} 
}

const mapApiDetailToForm = (item: any) => ({
  productId: item.productId,
  productName: item.productName,
  productCode: item.productCode,
  productTypeName: item.categoryName,
  productSpecification: item.spec,
  productUnit: item.unit,
  currentStock: item.beforeStock || 0,
  totalQuantity: item.quantityPurchased ?? item.quantity ?? 0,
  storedQuantity: item.inputNum ?? 0,
  currentQuantity: item.newInputNum ?? item.quantity ?? 0,
  storagelocationId: item.storagelocationId || null,
  unitPrice: item.price || 0,
  currentAmount: item.amount || 0,
  batchNumber: item.batchNo || '',
  productionDate: item.productionDate ? new Date(item.productionDate) : null,
  remarks: item.remark || '',
  positionOptions: [],
  positionLoading: false,
  positionId: item.positionId || null
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10px 0;
}

.pagination-info {
  margin-right: 20px;
  color: #606266;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  margin-top: 10px;
}

.el-table .el-table__row {
  cursor: pointer;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}

.el-table .current-row {
  background-color: #ecf5ff;
}

/* 用户选择对话框样式 */
.user-selection-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.search-section {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.content-section {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0;
}

.organization-tree {
  width: 250px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.tree-header {
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #303133;
}

.user-list {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-user-tag {
  margin-left: auto;
}

.user-grid {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  align-content: start;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.user-item:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.user-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  margin-right: 12px;
  flex-shrink: 0;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-account {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
}

/* 入库明细相关样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-info {
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-weight: 500;
  color: #303133;
}

.summary-info span {
  margin-right: 20px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}

.empty-state p {
  margin: 8px 0;
  font-size: 14px;
}

.empty-state p:first-of-type {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

:deep(.readonly-input .el-input__wrapper) {
  background-color: #f5f7fa;
}
</style>
